package m_suanfa.erchashu;

import java.util.ArrayList;
import java.util.List;

public class BinTree {

	private BinTree lChild;//左孩子
	private BinTree rChild;//右孩子
	private BinTree root; //根节点
	private Object data;//数据域
	private List<BinTree> datas;//存储所有节点
	public BinTree() {
		super();
	}
	public BinTree(BinTree lChild, BinTree rChild, Object data) {
		super();
		this.lChild = lChild;
		this.rChild = rChild;
		this.data = data;
	}
	public BinTree(Object data) {
		this(null,null,data) ;
	}
	
	//创建树
	public void createTree(Object[] objs){
		datas = new ArrayList<BinTree>();
		for (Object object : objs) {
			//带数据的bintree
			datas.add(new BinTree(object));
		}
		
		root = datas.get(0);//将第一个作为根节点
		for (int i = 0; i < objs.length/2; i++) {
			datas.get(i).lChild = datas.get(i*2+1);
			if (i*2+2 < datas.size()) {	//避免偶数的时候下标越界
				datas.get(i).rChild = datas.get(i*2+2);
			}
		}
	}
	
	//先序遍历
	/*
	 *1):访问根节点;
	  2):按先序遍历访问左子树
	  3):按先序遍历访问右子树
	 * */
	public void preOrder(BinTree root){
		if (null != root) {
			visit(root.getData());
			preOrder(root.getlChild());
			preOrder(root.getrChild());
		}
	}
	//中序遍历
	/*
	 * 1):按中序遍历左子树
	 2):访问根节点
	 3):按中序遍历访问右子树
	 * */
	public void inOrder(BinTree root){
		if (null != root) {
			inOrder(root.getlChild());
			visit(root.getData());
			inOrder(root.getrChild());
		}
	}
	//后序遍历
	/*
	 * 	 1):按后序遍历访问左子树
		 2):按后序遍历访问右子树
		 3):访问根节点
	 */
	public void afterOrder(BinTree root){
		if (null != root) {
			afterOrder(root.getlChild());
			afterOrder(root.getrChild());
			visit(root.getData());
		}
	}
	
	
	private void visit(Object obj) {
		System.out.print(obj+" ");
	}
	
	public BinTree getlChild() {
		return lChild;
	}
	public void setlChild(BinTree lChild) {
		this.lChild = lChild;
	}
	public BinTree getrChild() {
		return rChild;
	}
	public void setrChild(BinTree rChild) {
		this.rChild = rChild;
	}
	public BinTree getRoot() {
		return root;
	}
	public void setRoot(BinTree root) {
		this.root = root;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public List<BinTree> getDatas() {
		return datas;
	}
	public void setDatas(List<BinTree> datas) {
		this.datas = datas;
	}
	
	
	
	
	
}
